<template>
	<view :style="{'background-color':pageBg}" style="float: left;width: 100%;min-height: 100%;">

		<u-navbar is-back="true" title-color="" back-icon-color="" :border-bottom="false" :title="title"></u-navbar>

		<view style="float: left;width: 96%;margin-left: 2%;margin-top:30rpx;">
			<view v-for="(item, index) in itemList" @click="checkThis(item)">
				<view style="position: relative;" class="itemclass"
					:style="itemCheck.id == item.id?'background-color:#E8C895;border:1px solid #E8C895':'background-color:#f1f1f1;border:1px solid #E8C895'">
					<view
						style="position: absolute;top:-10px;right:-5px;border-radius: 10px;background-color: red;padding: 0px 10px;color: #ffffff;">
						{{itemCheck.discountName}}</view>
					<view style="font-size: 20px;font-weight: bold;color: #714213;padding: 30rpx 0rpx;">
						<text style="float: left;width: 100%;">{{item.name}}￥{{item.realPrice}}</text>
						<text
							style="color: #9D9CA0; text-decoration: line-through;font-size: 12px;width: 100%;float: left">原价￥{{item.rawPrice}}</text>
					</view>
				</view>
			</view>
		</view>

		<view style="float: left;width: 96%;margin-left: 2%;height: 60%;">
			<view
				style="float: left;width: 96%;margin-left: 2%;font-weight: bold;padding-bottom: 10px;margin-top: 20rpx;">
				<view style="float: left;padding-left: 10rpx;color: #C18B4D;">会员特权</view>
				<view style="float: right;padding-right: 10rpx;color: #C18B4D;" @click="show_bottom = true">
					用户须知<text class="tn-icon-help" style="padding-left: 2px;"></text>
				</view>
			</view>
			<scroll-view scroll-y="true" class="template-about tn-safe-area-inset-bottom"
				style="float: left;width: 100%;height: 100%;">
				<view class=" tn-margin-top-xl1 tn-padding-top-sm tn-padding-bottom-sm  bg-color-box css-theme"
					:class="[cueTheme]">
					<tn-list-cell class="css-theme" :class="[cueTheme]" :hover="true" :unlined="true" :fontSize="30"
						v-for="(item, index) in categories_search">
						<view class="tn-flex tn-flex-col-center">
							<view
								class="icon1__item--icon tn-flex tn-flex-row-center tn-flex-col-center tn-cool-bg-color-5 tn-color-white">
								<view :class="item.icon"></view>
							</view>
							<view class="tn-margin-left-sm tn-flex-1">
								<view>{{item.name}}</view>
								<view style="font-size: 12px;color: #ccc;margin-top: 10rpx;">{{item.remark}}</view>
							</view>
						</view>
					</tn-list-cell>
				</view>
			</scroll-view>
			<view v-if="platform == 1" :style="{'background-color':pageBg}"  class="css-theme" :class="[cueTheme]"
				style="float: left;width: 96%;margin-left: 2%;font-weight: bold;">
				<view style="float: left;">开通会员即视为同意<text style="color: #C18B4D;" @click="goMemAgree">《会员服务协议》</text></view>
			</view>
			<!-- <view style="float: left;width: 96%;margin-left: 2%;font-size: 10px;">
					温馨提示：会员服务购买后不支持退款，请确认后再付费开通！
			</view> -->
		</view>
		
		<!-- <view style="float: left;width:100%;">
			<view v-if="platform == 1" class=" tn-padding-top-sm tn-padding-bottom-sm tn-margin-left tn-margin-right" >
				<tn-list-cell style="margin-top: 27px;" :hover="true" :unlined="true" :radius="true" :fontSize="30"
					class=" css-theme" :class="[cueTheme]">
					<view class="tn-flex tn-flex-col-center">
						<view>
							<view class="tn-icon-payment-wechat"></view>
						</view>
						<view class="tn-margin-left-sm tn-flex-1">微信支付</view>
						<view class="tn-margin-left-sm">
							<view v-if="checkType == 1" @click="checkPay(1)"
								class="tn-margin-left-sm tn-icon-circle-fill" style="color: #18B998;font-size: 20px;">
							</view>
							<view v-else @click="checkPay(1)" class="tn-margin-left-sm tn-icon-circle"
								style="color: #9D9CA0;font-size: 20px;"></view>
						</view>
					</view>
				</tn-list-cell>
			</view>
			<view class="  tn-padding-bottom-sm tn-margin-left tn-margin-right" v-if="platform == 0">
				<tn-list-cell style="margin-top: 5px;" :hover="true" :unlined="true" :radius="true" :fontSize="30"
					class=" css-theme" :class="[cueTheme]">
					<view class="tn-flex tn-flex-col-center">
						<view>
							<view class="tn-icon-iphone"></view>
						</view>
						<view class="tn-margin-left-sm tn-flex-1">App内购买</view>
						<view class="tn-margin-left-sm">
							<view v-if="checkType == 2" @click="checkPay(2)"
								class="tn-margin-left-sm tn-icon-circle-fill" style="color: #18B998;font-size: 20px;">
							</view>
							<view v-else @click="checkPay(2)" class="tn-margin-left-sm tn-icon-circle"
								style="color: #9D9CA0;font-size: 20px;"></view>
						</view>
					</view>
				</tn-list-cell>
			</view>
		</view> -->

		<view class="nav-list-popup-apple" v-if="platform == 0" @click="payApple()">
			<text >立即支付</text>
		</view>
		<view class="nav-list-popup" v-if="platform == 1" >
			<!-- <text >立即支付</text> -->
			<view @click="payWx()" class="payView " style="background-color:#00C250;">
				<text class="tn-icon-payment-wechat" style="margin-right: 5px;"></text>微信支付</view>
			<view @click="payAlipay()" class="payView " style="background-color:#1378FE;">
				<text class="tn-icon-payment-alipay" style="margin-right: 5px;"></text>支付宝</view>
		</view>
		<tn-popup v-model="show_bottom" :zIndex="1001" :backgroundColor="pageBg" mode="bottom" :closeBtn="true"
			:borderRadius="20" height="60%">
			<view style="padding: 60rpx 30rpx 10rpx 30rpx; ">
				<view style="font-weight: bold;margin-bottom: 10px;">用户须知</view>
				<view style="margin-bottom: 10px;">
					1、刚上线，特推出终身VIP显示购买活动，福利即将下架！小伙伴们抓紧来撩！
				</view>
				<view style="margin-top: 10px;">
					2、会员服务购买后不支持退款，请确认之后再付费开通！
				</view>
				<view style="margin-top: 10px;">
					3、安卓、IOS会员通用！
				</view>
			</view>
		</tn-popup>
	</view>
</template>
<script>
	var _self
	export default {
		data() {
			return {
				show_bottom: false,
				checkType: 1,
				background: {
					backgroundColor: '#E8C895',
				},
				itemList: [{
						id: 1,
						name: '永久会员',
						realPrice: 68,
						rawPrice: '198',
						payid:''
					},
					{
						id: 2,
						name: '年会员',
						realPrice: 38,
						rawPrice: '128',
						payid:''
					},
					// {
					// 	id: 3,
					// 	name: '月会员',
					// 	money: 9.9,
					// 	remark: '3.3毛/天'
					// },					
				],
				
				categories_search: [{
						name: '记时间',
						remark: '记录时间，查看习惯、目标、事项等时间长度（已上线）',
						icon: 'tn-icon-time',
					},
					{
						name: '储物空间',
						remark: '收纳储物，让生活井井有条（已上线）',
						icon: 'tn-icon-gift',
					},
					{
						name: '积分奖惩',
						remark: '建立和谐积极向上家庭环境（已上线）',
						icon: 'tn-icon-percent',
					},
					{
						name: '记事情',
						remark: '让你记住所有想记录的事情（已上线）',
						icon: 'tn-icon-edit-form',
					},
					{
						name: '学习计划',
						remark: '学习积极分子必备（已上线）',
						icon: 'tn-icon-write-feather',
					},
					{
						name: '轻断食',
						remark: '定制简单、实用的轻断食计划（未上线）',
						icon: 'tn-icon-eat',
					},
					{
						name: '课程表',
						remark: '让学习不迷路（未上线）',
						icon: 'tn-icon-education',
					},
					{
						name: '计分器',
						remark: '记录赛事信息（未上线）',
						icon: 'tn-icon-level',
					},
					{
						name: '排班管理',
						remark: '排班、倒班、轮班，按时提醒（未上线）',
						icon: 'tn-icon-job',
					},
					{
						name: '记喝水',
						remark: '每天八杯水，变得美美美（未上线）',
						icon: 'tn-icon-watercup',
					},
					{
						name: '记便便',
						remark: '养成规律排便好习惯（未上线）',
						icon: 'tn-icon-floral',
					},
					
				],
				platform:1,
				wxStatus:0,
				alipayStatus:0,
				title:'',
				itemCheck:{}
				

			}
		},
		onLoad(options) {
			_self = this;
			
			
		},
		onShow() {
			if (uni.getSystemInfoSync().platform == 'ios') {
				this.platform=0
			} else if (uni.getSystemInfoSync().platform == 'android') {
				this.platform=1
			}
			
			this.checkAlipayApp()
			this.checkWxchatApp()
			
			uni.getStorage({
				key: 'user',
				success: function(res) {
					if (res.data) {
						_self.user = res.data
						console.log(_self.user)
						if(_self.user.member == 1){
							
							_self.title = "VIP至"+_self.user.expireTime.replace("-","/").replace("-","/")
						}else{
							_self.title = "会员"
						}
						
						setTimeout(function() {
							_self.getAmount()
							// _self.getCommonInfo()
						}, 200);
					}
				},
				fail: function(e) {
					uni.navigateTo({
						url: '../login/login'
					});
				}
			})
			
		},

		methods: {
			// 判断第三方程序(微信) 是否安装
			checkWxchatApp(){
			    if(plus.runtime.isApplicationExist({pname:'com.tencent.mm',action:'weixin://'})){
					this.wxStatus = 1
			    }else{
					this.wxStatus = 0
			    }
			},
			checkAlipayApp(){
			    if(plus.runtime.isApplicationExist({pname:'com.eg.android.AlipayGphone',action:'alipay://'})){
					this.alipayStatus = 1
			    }else{
					this.alipayStatus = 0
			    }
			},
			goMemAgree(){
				uni.navigateTo({
					url: '/pages/me/agreementMember'
				});
			},
			getCommonInfo() {
				var data = {
					userId: _self.user.id
				}
				this.$api.commonInfo(data).then((res) => {
					var resData = res;
			
					if (resData.code == "200") {
						_self.itemList[0].remark = +resData.data[0].info5;
						
						
					}
				})
			
			},
			pay() {
				if (this.checkType == 1) {
					this.payWx()
				} else {
					this.payApple()
				}
			},
			checkPay(type) {
				this.checkType = type
			},
			getAmount() {
				var data = {}
				
				console.log(this.platform )
				if(this.platform == 1){
					data = {
						type:0
					}
				}else{
					data = {
						type:1
					}
				}
				console.log(data)
				this.$api.appAmountNew(data).then((res) => {
					var resData = res;
					if (resData.code == "200") {
						console.log("==========================")
						console.log(resData)
						var datalist = []
						for(var i=0;i<resData.data.length;i++){
							var dataItem = resData.data[i]
							dataItem.name = dataItem.name.replace("安卓","").replace("苹果","")
							datalist.push(dataItem)
						}
						_self.itemList = datalist
						//下面是新的
						console.log(_self.itemList[0])
						_self.itemCheck = _self.itemList[0]
					}
				})

			},
			checkThis(item) {
				console.log(item)
				_self.itemCheck = item
			},
			payApple() {
				console.log("苹果支付")
				this.initIAP()
			},
			initIAP() {
				let that = this
				console.log(that.itemCheck.mark)
				
				plus.payment.getChannels((channels) => {
					for (var i in channels) {
						var channel = channels[i];
						console.log(channel)
						
						if (channel.id == 'appleiap') {
							console.log("苹果")
							let iap = channel;
							console.log(that.itemCheck.mark)
							//支付参数
							iap.requestOrder([that.itemCheck.mark], function(orderList) {
								//必须调用此方法才能进行 iap 支付 
								console.log('requestOrder success666: ' + JSON.stringify(orderList))
								that.applePay(orderList[0])
							}, function(e) {
								console.log('requestOrder failed: ' + JSON.stringify(e));
								// console.log('暂不支持苹果 iap 支付')
							});
							
							
							// iap.requestOrder(['shiguangjiid'], function(orderList) {
							// 	//必须调用此方法才能进行 iap 支付 
							// 	console.log('requestOrder success666: ' + JSON.stringify(orderList))
							// 	that.applePay(orderList[0])
							// }, function(e) {
							// 	console.log('requestOrder failed: ' + JSON.stringify(e));
							// 	// console.log('暂不支持苹果 iap 支付')
							// });
						}
					}
				}, function(e) {
					console.log("获取iap支付通道失败：" + e.message);
					
				});
				
			},
			applePay(para) {
				
				uni.showLoading({
					title: '支付请求中...'
				});
				uni.requestPayment({
					provider: 'appleiap',
					orderInfo: {
						productid: para.productid,
						username: this.currentUserName, // 用户标识
						optimize: true // 设置 optimize: true 解决丢单问题  
					},
					/* 
					orderInfo可传参数一览
					productid: (String 类型 )(必填) 商品的标识，你在苹果那里添加的商品标识 
					username: (String 类型 )(可选) 购买用户名称，我喜欢在这里传入订单号，这样支付成功时就可以获得订单号 
					quantity: (String 类型 )(可选) 商品数量，默认为 "1" 
					optimize:(Boolean)(可选) HX 3.1.10 版本新增参数，解决用户未绑定支付方式造成的丢单问题； 
					*/
					success: (e) => {
						uni.hideLoading();
						// uni.LTY.loaded();
						console.log("========支付成功===========")
						console.log(e)
						//这里把参数返回服务器进行二次验证 
						//这里再次验证是否订单真实有效
						
						var data = {
							userId:_self.user.id,
							receipt:e.transactionReceipt,
							type:1,
							payWay: 2,
							priceCode: _self.itemCheck.code
							
						}
						console.log(data)
						this.$api.applepay(data).then((res) => {
							var resData = res;
							if (resData.code == "200") {
								console.log("支付成功");
								
								let userInfo = uni.getStorageSync('user');
								if (userInfo) {
									userInfo.member = 1;
									// 更新缓存
									uni.setStorageSync('user', userInfo);
								}
								uni.navigateBack({
									delta: 1 
								});
							}
						})
						
					
					},
					fail: (e) => {
						uni.hideLoading();
						// uni.showModal({
						// 	content: "支付失败",
						// 	showCancel: false,
						// })
						
					},
					complete: () => {
						console.log("payment结束");
						// this.payShow = false;
						// this.payShow2 = false;
						uni.hideLoading();
					}


				})
			},

			payWx() {
				
				if(this.wxStatus == 0){
					uni.showToast({
						title: '请安装微信',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				console.log("微信支付")
				var data = {
					// total_fee=1&body=测试

					userId: _self.user.id,
					payWay: 0,
					type: _self.itemCheck.code
					// params:{
					// 	amount:0.01,
					// }
				}
				this.$api.payNew(data).then((res) => {
					var resData = res;
					console.log("==================")
					console.log(resData)
					if (resData.code == "200") {
						//订单对象，从服务器获取
						var orderInfo = {
							"appid": resData.data.appid, // 应用ID（AppID）
							"partnerid": resData.data.partnerid, // 商户号（PartnerID）
							"prepayid": resData.data.prepayid, // 预支付交易会话ID
							"package": resData.data.package, // 固定值
							"noncestr": resData.data.noncestr, // 随机字符串
							"timestamp": resData.data.timestamp, // 时间戳（单位：秒）
							"sign": resData.data.sign // 签名，这里用的 MD5 签名
						};
						console.log(orderInfo)
						uni.getProvider({
							service: 'payment',
							success: function(res) {
								console.log(res.provider)
								if (~res.provider.indexOf('wxpay')) {
									uni.requestPayment({
										"provider": "wxpay", //固定值为"wxpay"
										"orderInfo": orderInfo,
										success: function(res) {
											var rawdata = JSON.parse(res.rawdata);
											console.log("支付成功");
											
											let userInfo = uni.getStorageSync('user');
											if (userInfo) {
												userInfo.member = 1;
												// 更新缓存
												uni.setStorageSync('user', userInfo);
											}
											uni.navigateBack({
												delta: 1 
											});
										},
										fail: function(err) {
											console.log('支付失败:' + JSON.stringify(err));
										}
									});
								}
							}
						});


					}else{
						uni.showToast({
							title: resData.msg,
							duration: 2000,
							icon: 'none'
						});
					}
				})

			},
			
			payAlipay(){
				
				if(this.alipayStatus == 0){
					uni.showToast({
						title: '请安装支付宝',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				
				var data = {
					userId: _self.user.id,
					payWay: 1,
					type: _self.itemCheck.code
				}
				console.log(data)
				this.$api.payNew(data).then((res) => {
					var resData = res;
					console.log("==================")
					console.log(resData)
					//app_id=2015052600090779
					//&biz_content=%7B%22
					//timeout_express%22%3A%2230m%22%2C%22
					//seller_id%22%3A%22%22%2C%22
					//product_code%22%3A%22
					//QUICK_MSECURITY_PAY%22%2C%22
					//total_amount%22%3A%220.02%22%2C%22
					//subject%22%3A%221%22%2C%22
					//body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22
					//out_trade_no%22%3A%22314VYGIAGG7ZOYY%22%7D
					//&charset=utf-8
					//&method=alipay.trade.app.pay
					//&sign_type=RSA2
					//&timestamp=2016-08-15%2012%3A12%3A15
					//&version=1.0
					//&sign=MsbylYkCzlfYLy9PeRwUUIg9nZPeN9SfXPNavUCroGKR5Kqvx0nEnd3eRmKxJuthNUx4ERCXe552EV9PfwexqW%2B1wbKOdYtDIb4%2B7PL3Pc94RZL0zKaWcaY3tSL89%2FuAVUsQuFqEJdhIukuKygrXucvejOUgTCfoUdwTi7z%2BZzQ%3D
					if (resData.code == "200") {
						//订单对象，从服务器获取
						var orderInfo = resData.msg
						console.log(orderInfo)
						uni.getProvider({
							service: 'payment',
							success: function(res) {
								console.log(res.provider)
								if (~res.provider.indexOf('alipay')) {
									uni.requestPayment({
										"provider": "alipay", 
										"orderInfo": orderInfo,
										success: function(res) {
											var rawdata = JSON.parse(res.rawdata);
											console.log("支付成功");
											
											let userInfo = uni.getStorageSync('user');
											if (userInfo) {
												userInfo.member = 1;
												// 更新缓存
												uni.setStorageSync('user', userInfo);
											}
											uni.navigateBack({
												delta: 1 
											});
										},
										fail: function(err) {
											console.log('支付失败:' + JSON.stringify(err));
										}
									});
								}
							}
						});
				
				
					}else{
						uni.showToast({
							title: resData.msg,
							duration: 2000,
							icon: 'none'
						});
					}
				})
			},
		}
	}
</script>
<style lang="scss">
	page {
		height: 100%;
		display: flex;
		width: 100%;
		margin: 0;
		background-color: $page-bg !important;
	}

	.css-theme {
		@include text-color();
		@include base-background();
		@include border-color();
		@include shadow-color();
	}

	.itemclass {
		float: left;
		width:44%;
		margin-left: 4%;
		// margin-left: 7%;
		text-align: center;
		// border: 1px solid #C18B4D;
		border-radius: 5px;
		padding: 30rpx 0rpx;
		// box-shadow: 5px 5px 25px 5px rgba(0, 0, 0, 0.07);
	}
	.nav-list-popup-apple {
		position: absolute;
		bottom: 20px;
		width: 80%;
		margin-left: 10%;
		text-align: center;
		background-color: #E8C895;
		border-radius: 5px;
		justify-content: space-between;
		color: #714213;
		height: 42px;
		line-height: 42px;
		font-weight: bolder;
	
	}
	.nav-list-popup {
		position: absolute;
		bottom: 20px;
		width: 80%;
		margin-left: 10%;
		text-align: center;
		// background-color: #E8C895;
		border-radius: 5px;
		justify-content: space-between;
		color: #714213;
		height: 42px;
		line-height: 42px;
		font-weight: bolder;

	}
	.payView{
		float: left;
		width: 41%;
		margin-left: 6%;
		border-radius: 30px;
		color: white;
		z-index: 10;
	}

	.template-about {
		// background-color: #ffffff !important;
		padding-bottom: 40rpx;
	}

	.bg-color-box {
		// background-color: #fff;
		border-radius: 20rpx
	}


	/* 页面 start*/
	.about-shadow {
		border-radius: 15rpx;
		box-shadow: 0rpx 0rpx 50rpx 0rpx rgba(0, 0, 0, 0.07);
	}

	.about {

		&__wrap {
			position: relative;
			z-index: 1;
			// margin: 20rpx 30rpx;
			margin-top: -330rpx;
		}
	}

	/* 页面 end*/

	/* 用户信息 end */
	/* 图标容器1 start */
	.icon1 {
		&__item {
			// width: 30%;
			background-color: #FFFFFF;
			border-radius: 10rpx;
			padding: 30rpx;
			margin: 20rpx 10rpx;
			transform: scale(1);
			transition: transform 0.3s linear;
			transform-origin: center center;

			&--icon {
				width: 40rpx;
				height: 40rpx;
				font-size: 28rpx;
				border-radius: 50%;
				position: relative;
				z-index: 1;

				&::after {
					content: " ";
					position: absolute;
					z-index: -1;
					width: 100%;
					height: 100%;
					left: 0;
					bottom: 0;
					border-radius: inherit;
					opacity: 1;
					transform: scale(1, 1);
					background-size: 100% 100%;
					background-image: url(https://tnuiimage.tnkjapp.com/cool_bg_image/icon_bg.png);
				}
			}
		}
	}


	// .tn-margin-top-xl1 {
	// 	margin-top: 20rpx;
	// }
</style>